package com.work.formaldehyde.homefragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activity.KePuListActivity;
import com.work.formaldehyde.activity.KePuXQActivity;
import com.work.formaldehyde.mainadapter.KePuAdapter;
import com.work.formaldehyde.model.KePuBanner;
import com.work.formaldehyde.model.KePuHomeModel;
import com.work.formaldehyde.model.KePuModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class KepuFragment extends Fragment implements View.OnClickListener, OnBannerListener, AdapterView.OnItemClickListener {
    //用于获取视图
    private View root;
    //三个图片视图
    private RelativeLayout kepu_one_rela, kepu_two_rela, kepu_the_rela;
    //    private ImageView kepu_one, kepu_two, kepu_the;
    private TextView kepu_one_text, kepu_two_text, kepu_the_text;
    private LinearLayout baba;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.home_listhead, container, false);//初始加载
        if (ApiUtils.isNetworkConnected(getActivity()))
            InitView(root);
        return root;
    }

    private Banner mBanner;
    private MyImageLoader mMyImageLoader;
    private RelativeLayout kp_title;
    private TabLayout list_tab;

    private void initViews() {
        mMyImageLoader = new MyImageLoader();
        //设置样式，里面有很多种样式可以自己都看看效果
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mBanner.setImageLoader(mMyImageLoader);
        //设置轮播的动画效果,里面有很多种特效,可以都看看效果。
        mBanner.setBannerAnimation(Transformer.DepthPage);
        //轮播图片的文字
        mBanner.setBannerTitles(imageTitle);
        //设置轮播间隔时间
        mBanner.setDelayTime(3000);
        //设置是否为自动轮播，默认是true
        mBanner.isAutoPlay(true);
        //设置指示器的位置，小点点，居中显示
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置图片加载地址
        mBanner.setImages(imagePath)
                //轮播图的监听
                .setOnBannerListener(this)
                //开始调用的方法，启动轮播图。
                .start();

    }

    private ImageView kepu_one, kepu_two, kepu_the;
    private ArrayList<KePuModel.data> new_list_view;
    private ListView kepu_list;
    public static KePuModel kePuModel;

    /**
     * 初始加载视图
     */
    public void Init(View view) {
        kepu_list = view.findViewById(R.id.kepu_list);
        new_list_view = new ArrayList<>();
        kepu_list.setOnItemClickListener(this);
        okHttp_postFromParameters();
        okHttp_postFromParameters1();
        okhttpgetkepu();
        Map<String, Object> music = new HashMap<String, Object>();
        music.put("科普页面", "1");//自定义参数：音乐类型，值：流行
        MobclickAgent.onEventObject(getActivity(), "polular_science", music);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent tokpxq = new Intent(getActivity(), KePuXQActivity.class);
        tokpxq.putExtra("id", (i - 1) + "");
        tokpxq.putExtra("url", new_list_view.get(i-1).getUrl() + "");
        tokpxq.putExtra("num", "0");
        startActivity(tokpxq, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
    }

    /**
     * 图片加载类
     */
    private class MyImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context.getApplicationContext())
                    .load(path)
                    .into(imageView);
        }
    }

    private int type =5;
    private boolean is_onein = false;

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody;
                    Request request;
                        request = new Request.Builder().get().url(Url.GETKEPUWENZHANGLIST + "?type="+type).build();
//                        formBody = new FormBody.Builder().add("type", type + "")
//                                .build();
//                    Request request = new Request.Builder().url(Url.GETKEPU).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1.sendMessage(message);
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).

                start();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
//                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        if (is_onein)
                            new_list_view.clear();
                        Gson gson = new Gson();
                        kePuModel = gson.fromJson(msg.obj.toString(),
                                KePuModel.class);
                        KePuAdapter myAdapter = new KePuAdapter(new_list_view,
                                getActivity());
                        new_list_view.addAll(kePuModel.getData());
                        kepu_list.setAdapter(myAdapter);
                        myAdapter.notifyDataSetChanged();
                        if (!is_onein)
                            is_onein = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    public static KePuHomeModel kePuHomeModel;

    private void okhttpgetkepu() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody;
//                    formBody = new FormBody.Builder()
//                            .build();
//                    Request request = new Request.Builder().url(Url.GETKEPUHOME).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    getkp.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.WENZHANGLIST + "?pid=1").build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                getkp.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).

                start();
    }

    private boolean truechick = false;

    public Handler getkp = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        truechick = true;
                        Gson gson = new Gson();
                        kePuHomeModel = gson.fromJson(msg.obj.toString(),
                                KePuHomeModel.class);
                        kepu_one_text.setText(kePuHomeModel.getData().get(0).getName());
                        kepu_two_text.setText(kePuHomeModel.getData().get(1).getName());
                        kepu_the_text.setText(kePuHomeModel.getData().get(2).getName());
                        ApiUtils.GET_IMAGE(getActivity(), kePuHomeModel.getData().get(0).getImage(), kepu_one);
                        ApiUtils.GET_IMAGE(getActivity(), kePuHomeModel.getData().get(1).getImage(), kepu_two);
                        ApiUtils.GET_IMAGE(getActivity(), kePuHomeModel.getData().get(2).getImage(), kepu_the);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    /**
     * 初始加载视图
     */
    public void InitView(View v) {
        Init(v);
        ListInit();
        View view = getActivity().getLayoutInflater().inflate(
                R.layout.fragment_kepu, kepu_list, false);
        kepu_list.addHeaderView(view);
        mBanner = view.findViewById(R.id.banner);
        kepu_one = view.findViewById(R.id.kepu_one);
        kepu_two = view.findViewById(R.id.kepu_two);
        kepu_the = view.findViewById(R.id.kepu_the);
        baba = view.findViewById(R.id.baba);
        kp_title = view.findViewById(R.id.kp_title);
        int titleheight = ApiUtils.getStatusBarHeight(getActivity());
        kp_title.setPadding(0, titleheight, 0, 0);
        kepu_one_rela = view.findViewById(R.id.kepu_one_rela);
        kepu_one_rela.setOnClickListener(this);
        kepu_two_rela = view.findViewById(R.id.kepu_two_rela);
        kepu_two_rela.setOnClickListener(this);
        kepu_the_rela = view.findViewById(R.id.kepu_the_rela);
        kepu_the_rela.setOnClickListener(this);
        kepu_one_text = view.findViewById(R.id.kepu_one_text);
        kepu_two_text = view.findViewById(R.id.kepu_two_text);
        kepu_the_text = view.findViewById(R.id.kepu_the_text);
        list_tab = view.findViewById(R.id.list_tab);
        tab_init();
    }

    public void tab_init() {
        list_tab.addTab(list_tab.newTab().setText("综合"));
        list_tab.addTab(list_tab.newTab().setText("甲醛"));
        list_tab.addTab(list_tab.newTab().setText("危害"));
        list_tab.addTab(list_tab.newTab().setText("健康"));
        list_tab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 开启Fragment事务
                if (tab.getText().equals("综合")) {
                    if (ApiUtils.isNetworkConnected(getActivity())) {
                        type = 5;
//                        ApiUtils.windows(getActivity(), list_tab, "加载中..");
//                        new Handler().postDelayed(new Runnable() {
//                            public void run() {
//                                ApiUtils.closepopup();
//                            }
//                        }, 10000);
                        okHttp_postFromParameters();
                    }
                }
                if (tab.getText().equals("甲醛")) {
                    if (ApiUtils.isNetworkConnected(getActivity())) {
                        type = 7;
//                        ApiUtils.windows(getActivity(), list_tab, "加载中..");
//                        new Handler().postDelayed(new Runnable() {
//                            public void run() {
//                                ApiUtils.closepopup();
//                            }
//                        }, 10000);
                        okHttp_postFromParameters();
                    }
                }
                if (tab.getText().equals("危害")) {
                    if (ApiUtils.isNetworkConnected(getActivity())) {
                        type = 8;
//                        ApiUtils.windows(getActivity(), list_tab, "加载中..");
//                        new Handler().postDelayed(new Runnable() {
//                            public void run() {
//                                ApiUtils.closepopup();
//                            }
//                        }, 10000);
                        okHttp_postFromParameters();
                    }
                }
                if (tab.getText().equals("健康")) {
                    if (ApiUtils.isNetworkConnected(getActivity())) {
                        type = 9;
//                        ApiUtils.windows(getActivity(), list_tab, "加载中..");
//                        new Handler().postDelayed(new Runnable() {
//                            public void run() {
//                                ApiUtils.closepopup();
//                            }
//                        }, 10000);
                        okHttp_postFromParameters();
                    }
                }
//                if (tab.getText().equals("其他")) {
//                    if (ApiUtils.isNetworkConnected(getActivity())) {
//                        type = 4;
//                        ApiUtils.windows(getActivity(), list_tab, "加载中..");
//                        new Handler().postDelayed(new Runnable() {
//                            public void run() {
//                                ApiUtils.closepopup();
//                            }
//                        }, 10000);
//                        okHttp_postFromParameters();
//                    }
//                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void tokepulist(String itemid, String name) {
        if (truechick) {
            Intent tokplist = new Intent(getActivity(), KePuListActivity.class);
            tokplist.putExtra("type", itemid);
            tokplist.putExtra("name", name);
            startActivity(tokplist, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
        } else {
            ApiUtils.SetToast(getActivity(), "加载中~");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.kepu_one_rela:
                tokepulist("2", kePuHomeModel.getData().get(0).getName());
                break;
            case R.id.kepu_two_rela:
                tokepulist("3", kePuHomeModel.getData().get(1).getName());
                break;
            case R.id.kepu_the_rela:
                tokepulist("4", kePuHomeModel.getData().get(2).getName());
                break;
        }
    }

    private ArrayList<String> imagePath;
    private ArrayList<String> imageTitle;
    private ArrayList<String> msgtext;

    /**
     * 用于遍历集合
     */
    public void ListInit() {
        imagePath = new ArrayList<>();
        imageTitle = new ArrayList<>();
        msgtext = new ArrayList<>();
        imageTitle.add("我是海鸟一号");
        imageTitle.add("我是海鸟二号");
        imageTitle.add("我是海鸟三号");
        msgtext.add("恭喜【简单爱】完成每日任务，获得0.10元奖");
        msgtext.add("恭喜【简单爱】完成每日任务，获得0.20元奖");
        msgtext.add("恭喜【简单爱】完成每日任务，获得0.30元奖");
    }

    /**
     * Banner 实现点击事件
     *
     * @param position
     */
    @Override
    public void OnBannerClick(int position) {
        if (!jcbner.getData().get(position).getImg().equals("")) {
            Intent tokpxq = new Intent(getActivity(), KePuXQActivity.class);
            tokpxq.putExtra("id", position + "");
            tokpxq.putExtra("url", jcbner.getData().get(position).getUrl() + "");
            tokpxq.putExtra("num", "2");
            startActivity(tokpxq, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
        }
    }

    private void okHttp_postFromParameters1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder()
//                            .add("type", "kp").build();
//                    Request request = new Request.Builder().url(Url.GETBANNER).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.GETBANNERS + "kp").build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public static KePuBanner jcbner;
    public Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        jcbner = gson.fromJson(msg.obj.toString(),
                                KePuBanner.class);
                        ListInit();
                        for (int a = 0; a < jcbner.data.size(); a++) {
                            imagePath.add(jcbner.data.get(a).getImg());
                        }
                        initViews();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}